package mytest.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import mytest.util.JenkinsServer;
import mytest.util.RequestUtil;
import mytest.util.Response;
import test.testcase.TestJob;
import test.testcase.dao.JobDao;
import test.testcase.dao.TestCaseDao;
import test.utils.JsonResult;

@Controller @RequestMapping(value = "/job", produces = "application/json; charset=utf-8")
@CrossOrigin
public class job {
	
	@RequestMapping(value = "/getlist")
	public @ResponseBody String getJobList(HttpServletRequest request) {
		return JobDao.getJobList(RequestUtil.getProjectId(request)).toResponse();
	}
	
	@RequestMapping(value = "/getlist/{projectid}")
	public @ResponseBody String getJobList(@PathVariable String projectid, HttpServletRequest request) {
		return JobDao.getJobListByprojectid(projectid).toResponse();
	}
	
	@RequestMapping(value = "/getExcuteLoglist")
	public @ResponseBody String getExcuteLoglist(HttpServletRequest request) {
		int start = RequestUtil.getStartPage(request);
		int end = RequestUtil.getEndPage(request);
		String status = request.getParameter("status");
		if (status == null || status.equals("ALL")) {
			return JobDao.getJobExcuteLogList(RequestUtil.getProjectId(request), start, end).toResponse();
		}
		return JobDao.getJobExcuteLogListByStatus(RequestUtil.getProjectId(request), start, end, status).toResponse();
	}
	
	@RequestMapping(value = "/getcaselist/{jobid}")
	public @ResponseBody String getJobCaseList(@PathVariable String jobid, HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");  
		String caseid = request.getParameter("caseid");
		String casename = request.getParameter("casename");
		String channel = request.getParameter("channel");
		StringBuffer where = new StringBuffer();
		if (!"ALL".equals(caseid) && caseid != null) {
			where.append(" and b.id="+caseid);
		}
		if (!"ALL".equals(casename) && casename != null) {
			where.append(" and b.casename like '%"+casename+"%'");
		}
		if(!"ALL".equals(channel) && channel != null) {
			where.append(" and b.channel='"+channel+"'");
		}
		where.append(" and b.projectid='"+RequestUtil.getProjectId(request)+"'");
		return JobDao.getJobCases(jobid, RequestUtil.getStartPage(request), RequestUtil.getEndPage(request), where.toString()).toResponse();
	}
	
	@RequestMapping(value = "/{jobid}/removecase/{caseid}")
	public @ResponseBody String removecase(@PathVariable String jobid, @PathVariable String caseid) {
		JobDao.removeCaseFromJob(jobid, caseid);
		Response response = new Response();
		response.setRetMessage("操作成功");
		return response.toString();
	}
	
	@RequestMapping(value = "/{jobid}/removecases")
	public @ResponseBody String removecases(@PathVariable String jobid, @RequestBody String body) {
		JSONArray array = new JSONArray(body);
		StringBuffer aBuffer = new StringBuffer();
		for(int i=0;i<array.length();i++) {
			if (aBuffer.toString().equals("")) {
				aBuffer.append(array.getJSONObject(i).getString("id"));
			}else {
				aBuffer.append(","+array.getJSONObject(i).getString("id"));
			}
		}
		JobDao.removeCasesFromJob(jobid, aBuffer.toString());
		return new Response().setRetMessage("操作成功").toString();
	}
	
	@RequestMapping(value = "/{jobid}/addcase/{caseid}")
	public @ResponseBody String addJobCase(@PathVariable String jobid, @PathVariable String caseid) {
		JobDao.addJobCase(jobid, caseid);
		Response response = new Response();
		response.setRetMessage("操作成功");
		return response.toString();
	}
	
	@RequestMapping(value = "/{jobid}/addcase")
	public @ResponseBody String addJobCaseMore(@RequestBody String body, @PathVariable String jobid) {
		JSONArray array = new JSONArray(body);
		StringBuffer aBuffer = new StringBuffer();
		for(int i=0;i<array.length();i++) {
			if (aBuffer.toString().equals("")) {
				aBuffer.append("values "+"("+jobid+","+array.getJSONObject(i).getString("id")+")");
			}else {
				aBuffer.append(","+"("+jobid+","+array.getJSONObject(i).getString("id")+")");
			}
		}
		JobDao.addJobCases(aBuffer.toString());
		return new Response().setRetMessage("操作成功").toString();
	}
	
	@RequestMapping(value = "/{jobid}/getnotcontaincases")
	public @ResponseBody String getnotcontaincases(@PathVariable String jobid, HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");  
		String caseid = request.getParameter("caseid");
		String casename = request.getParameter("casename");
		String channel = request.getParameter("channel");
		String projectid = RequestUtil.getProjectId(request);
		StringBuffer where = new StringBuffer();
		if (!"ALL".equals(caseid) && caseid != null) {
			where.append(" and a.id="+caseid);
		}
		if (!"ALL".equals(casename) && casename != null) {
			where.append(" and a.casename like '%"+casename+"%'");
		}
		if(!"ALL".equals(channel) && channel != null) {
			where.append(" and a.channel='"+channel+"'");
		}
		where.append(" and a.projectid='"+projectid+"'");
		return TestCaseDao.getJobNotContainCases(jobid, RequestUtil.getStartPage(request), RequestUtil.getEndPage(request), where.toString()).toResponse();
	}
	
	@RequestMapping(value = "/add")
	public @ResponseBody String add(HttpServletRequest request, @RequestBody String body) {
		String userid = RequestUtil.getUserId(request);
		JsonResult result = JsonResult.parse(body);
		String title = result.read("title").toString();
		String desc = result.read("desc").toString();
		String projectid = RequestUtil.getProjectId(request);
		return JobDao.addJob(title, desc, userid, projectid).toResponse();
	}
	
	@RequestMapping(value = "/del/{id}")
	public @ResponseBody String add(@PathVariable String id) {
		JsonResult  result = JobDao.del(id);
		if (result == null) {
			return new Response().setFalse("先清空用例再删除").toString();
		}
		return result.toResponse();
	}
	
	@RequestMapping(value = "/dellog/{id}")
	public @ResponseBody String delLog(@PathVariable String id) {
		TestJob job = JobDao.getJobByExcuteId(id);
		JenkinsServer jenkins = new JenkinsServer(job.getProjectid());
		if (job.getBuildNumber() != null && !"".equals(job.getBuildNumber())) {
			jenkins.stopBuild(job.getBuildNumber());
		}
		JsonResult  result = JobDao.delJobLog(id);
		return result.toResponse();
	}
}
